package wangjg.coco.common;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;

import org.mozilla.intl.chardet.nsDetector;
import org.mozilla.intl.chardet.nsICharsetDetectionObserver;
import org.mozilla.intl.chardet.nsPSMDetector;

public class CharsetDetector{

	private boolean _found = false;
	private String result;
	private String[] probableCharsets;

	public void detect(InputStream in) throws Exception {
		nsDetector det = new nsDetector(nsPSMDetector.ALL);
		det.Init(new nsICharsetDetectionObserver(){
			public void Notify(String charset) {
				_found = true;
				result = charset;
			}});
		byte[] buf = new byte[1024];
		boolean isAscii = true;
		int len;
		BufferedInputStream imp = new BufferedInputStream(in);
		while ((len = imp.read(buf, 0, buf.length)) != -1) {
			if (isAscii)
				isAscii = det.isAscii(buf, len);
			if (!isAscii){
				boolean done = det.DoIt(buf, len, false);
				if(done)break;
			}
		}
		det.DataEnd();
		if (isAscii) {
			_found = true;
			this.result = "ASCII";
		}

		if (!_found) {
			this.probableCharsets = det.getProbableCharsets();
		}
	}
	
	public String[] getProbableCharsets() {
		return probableCharsets;
	}

	public String getResult() {
		return result;
	}

	public String selectCharset(String...charsets){
		if(probableCharsets==null||probableCharsets.length==0){
			return null;
		}
		for(String charset:charsets){
			for(String cs:this.probableCharsets){
				if(charset!=null && cs!=null && charset.toUpperCase().equals(cs.toUpperCase())){
					return charset;
				}
			}
		}
		return null;
	}

	public String getProbableSeq() {
		StringBuilder sb = new StringBuilder();
		for(int i=0;probableCharsets!=null&&i<probableCharsets.length;i++){
			if(i>0){
				sb.append('/');
			}
			sb.append(probableCharsets[i]);
		}
		return sb.toString();
	}

	@Override
	public String toString() {
		return "FileCharsetDetector [found=" + _found + ", result=" + result
				+ ", probableCharsets=" + Arrays.toString(probableCharsets)
				+ "]";
	}

	public static void main(String argv[]) {
		String filepath = "E:/gewaworkspace/gptbs/trunk/src/test/java/test/test/Test.java";
		CharsetDetector detector = new CharsetDetector();
		FileInputStream in = null;
		try {
			in = new FileInputStream(filepath);
			detector.detect(in);
			System.out.println("*************************");
			System.out.println(filepath);
			System.out.println(detector);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
				try {
					if(in!=null)in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
	}

}
